
<?php
session_start();
if ($_SESSION['Status'] != '1') {
    header('Location: signup.php');
}
$id = $_SESSION['name'];

// get the file field as the name of avatar
if (isset($_FILES["photo"]["name"]) && $_FILES["photo"]["tmp_name"] != ""){
	$fileName = $_FILES["photo"]["name"];
        $fileTmpLoc = $_FILES["photo"]["tmp_name"];
	$fileType = $_FILES["photo"]["type"];
	$fileSize = $_FILES["photo"]["size"];
	$fileErrorMsg = $_FILES["photo"]["error"];
	$kaboom = explode(".", $fileName);
	$fileExt = end($kaboom);
	list($width, $height) = getimagesize($fileTmpLoc);
	if($width < 10 || $height < 10){
		//header("location: ../message.php?msg=ERROR: That image has no dimensions");
		 echo "<script type='text/javascript'>alert(' That image has no dimensions');</script>";
        exit();	
	}
	$db_img_name = rand(100000000000,999999999999).".".$fileExt;
	if($fileSize > 1048576) {
		//header("location: ../message.php?msg=ERROR: Your image file was larger than 1mb");
		echo "<script type='text/javascript'>alert(' Your image file was larger than 1mb');</script>";
		exit();	
	} else if (!preg_match("/\.(gif|jpg|png)$/i", $fileName) ) {
		//header("location: ../message.php?msg=ERROR: Your image file was not jpg, gif or png type");
		echo "<script type='text/javascript'>alert(' Your image file was not jpg, gif or png type');</script>";
		exit();
	} else if ($fileErrorMsg == 1) {
		
		echo "<script type='text/javascript'>alert(' An unknown error occurred');</script>";
		exit();
	}
	$sql = "SELECT * FROM `users` WHERE `email`='$id' LIMIT 0, 30 ";
	
	$query = mysqli_query($con, $sql);
	$row = mysqli_fetch_array($query, MYSQLI_ASSOC);
	//$row = mysqli_fetch_row($query);
	$pid = $row["email"];
	$image = $row["photo"];
	if($image != ""){
		$picurl = "user/$pid/$image"; 
	    if (file_exists($picurl)) { unlink($picurl); }
	}
	$moveResult = move_uploaded_file($fileTmpLoc, "user/$pid/$db_img_name");
	if ($moveResult != true) {
		//header("location: ../message.php?msg=ERROR: File upload failed");
		echo "<script type='text/javascript'>alert(' File upload failed');</script>";
		exit();
	}
	//done ------------------------------------------------------------------------------------------
	//-----------------------------------------------------------------------------------------------
	
	include('image_resize.php');
	$target_file = "user/$pid/$db_img_name";
	$resized_file = "user/$pid/$db_img_name";
	$wmax = 200;
	$hmax = 300;
	img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt);
	$sql = "UPDATE `users` SET `Image`='$db_img_name' WHERE `email`='$id'";
	
	$query = mysqli_query($con, $sql);
	echo "<script type='text/javascript'>alert('You have successfully uploaded your profile picture');</script>";
	mysqli_close($con);
	
	header("location: ../ProfileMain.php?successfully uploaded?u=$u");
	exit();
}
?>